package dataStructure.xmg1.leetCode.binaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 226。翻转二叉树
 * https://leetcode-cn.com/problems/invert-binary-tree/
 *
 * @author: vince_zww
 * @date: 2020/12/22 21:23
 * @desceription:
 */
public class LeetCode_226 {
    //前序遍历
//    public TreeNode invertTree(TreeNode root) {
//        if (root==null)return root;
//
//        TreeNode tmp = root.left;
//        root.left = root.right;
//        root.right = tmp;
//
//        invertTree(root.left);
//        invertTree(root.right);
//
//        return root;
//    }
    //后序遍历
//    public TreeNode invertTree(TreeNode root) {
//        if (root==null)return root;
//
//        invertTree(root.left);
//        invertTree(root.right);
//
//        TreeNode tmp = root.left;
////        root.left = root.right;
////        root.right = tmp;
//
//        return root;
//    }

    //中序遍历
//    public TreeNode invertTree(TreeNode root) {
//        if (root==null)return root;
//
//        invertTree(root.left);
//
//        TreeNode tmp = root.left;
//        root.left = root.right;
//        root.right = tmp;
//
//        invertTree(root.left);
//        return root;
//    }

    //层序遍历
    public TreeNode invertTree(TreeNode root) {
        if (root==null)return root;
        Queue<TreeNode> queue = new LinkedList<>();
        //入队
        queue.offer(root);
        while (!queue.isEmpty()) {
            //出队
            TreeNode node = queue.poll();

            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;

            if (node.left != null) {
                //入队
                queue.offer(node.left);
            }
            if (node.right != null) {
                //入队
                queue.offer(node.right);
            }
        }
        return root;
    }

}
